package leetcode.doublepointer;

import java.util.Arrays;

//189. 旋转数组
public class Rotate {
    public static void main(String[] args) {
        int[] data = {1, 2, 3, 4};
        rotate(data, 3);
        System.out.println(Arrays.toString(data));
    }

    //类似循环队列
    public static void rotate(int[] nums, int k) {
        int[] f = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            f[(i + k) % nums.length] = nums[i];
        }
        System.arraycopy(f, 0, nums, 0, nums.length);
    }

    //翻转数组
    public static void rotate2(int[] nums, int k) {
        k %= nums.length;
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.length - 1);

    }

    //利用双指针翻转
    public static void reverse(int[] nums, int start, int end) {
        int p = start;
        int q = end;
        while (p <= q) {
            int temp = nums[p];
            nums[p] = nums[q];
            nums[q] = temp;
            p++;
            q--;
        }
    }

    // 面试题 01.07. 旋转矩阵

    /***
     * 按照旋转后的数组和原数组找规律
     * @param matrix
     */
    public void rotateP(int[][] matrix) {
        int[][] newMatrix = new int[matrix.length][matrix[0].length];
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                newMatrix[j][matrix[0].length - i - 1] = matrix[i][j];
            }
        }
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix.length; j++) {
                matrix[i][j] = newMatrix[i][j];
            }
        }
    }
}
